<template>
    <div>
      <ddHead
        :selectedNum="selectedNum"
        :list=" fruitList"
        @clear="clearHandler"
        @changeCheck="changeCheck"/>
      <ddMain
      :list=" fruitList"
      @changeNum="changeNumHandler"
      @toDel="delItem"/>
      <ddFoot
        :selectedNum="selectedNum"
        :totalPrice="totalPrice"
      />
    </div>
  </template>
  
  <script>
  import ddHead from './components/dd-head.vue'
  import ddMain from './components/dd-main.vue'
  import ddFoot from './components/dd-foot.vue'
  export default {
    components: {
      ddHead,
      ddMain,
      ddFoot
    },
    data(){
      return {
         fruitList:[
          {id:111,img:require('@/assets/6.png') , name:'赣南脐橙(中果)6个约1kg',type:'7.08折',price:'¥9.79',isChecked:false,num:1},
          {id:222,img:require('@/assets/5.png') , name:'[酸溜溜]菲律宾凤梨1个800g',type:'削皮,切块',price:'¥11.9',isChecked:false,num:1},
          {id:333,img:require('@/assets/4.png') , name:'百香果 300g/份',type:'库存紧张',price:'¥9.79',isChecked:false,num:1},
          {id:444,img:require('@/assets/3.png') , name:'迷你樱桃山楂 300g/份',type:'',price:'¥9.9',isChecked:false,num:1},
          {id:444,img:require('@/assets/7.png') , name:'多彩小番茄 400g/份',type:'',price:'¥14.9',isChecked:false,num:1},
          {id:444,img:require('@/assets/2.png') , name:'供港基地YOOM番茄 218g/盒',type:'库存紧张',price:'¥13.9',isChecked:false,num:1},
          {id:444,img:require('@/assets/1.png') , name:'红心芭乐(番石榴)2个 300g/份',type:'库存紧张',price:'¥12.9',isChecked:false,num:1}
        ]
      }
    },
    computed:{
      selectedNum(){
        return this.fruitList.filter(obj => obj.isChecked).reduce((sum, obj) => sum + obj.num, 0)
      },
      totalPrice(){
        return this.fruitList.filter(obj => obj.isChecked).reduce((sum, obj)=> sum + obj.num * obj.price , 0)
      }
    },
    methods:{
      changeCheck(val){
        this. fruitList.forEach(obj => obj.isChecked = val);
      },
      changeNumHandler(type, id){
        this. fruitList.forEach(obj => {
          if(obj.id === id) {
            if(type === 'add'){
              obj.num += 1
            } else{
              obj.num -= 1
            }
          }
        })
      },
      delItem(id){
        let targetIndex = this.fruitList.findIndex(obj => obj.id === id)
        console.log('targetIndex',targetIndex);
        targetIndex !== -1 ? this.fruitList.splice(targetIndex, 1) : ''
      },
      clearHandler(){
        this.fruitList = []
      }
    }
  }
  </script>
  
  <style>
  
  </style>